import axios from 'axios'
import {
  baseURL
} from '@/config'
class HttpRequest {

  constructor(baseUrl = baseURL) { //传入 一个参数 bseUrl ,传入一个默认值 为 baseURL
    //new 一个 构造函数的实例化对象的时候传入的参数
    this.baseUrl = baseUrl
    this.queue = [] //队列
  }

  getInsideConfig() {
    const config = {
      baseUrl: this.baseUrl
    }
    return config
  }

  interceptors(instance, url) {
    //添加一个请求拦截器
    instance.interceptors.request.use(config => {
      //添加全局的loading...
      //Spin.show()   遮罩层组件的显示
      if (!Object.keys(this.queue).length)
        // Spin.show() 
        this.queue[url] = true
      return config

    }, error => {
      return Promise.reject(error)
    })
    //定义一个响应拦截器
    instance.interceptors.response.use(res => {
      console.log(res);
      delete this.queue[url]
      const {
        data,
        status
      } = res
      return {
        data,
        status
      }
    }, error => {
      delete this.queue[url]
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance)
    return instance(options)
  }

}

export default HttpRequest